$(function () {
    $('#releaseTimeBeginId,#releaseTimeEndId').datetimepicker({
        lang:'ch',format:'Y-m-d','timepicker': false,'datepicker':true,
        onSelectDate: function(dateText, inst) {
            this.hide();
        }});
    $("#jqGrid").jqGrid({
        url: baseURL + 'sys/teach/list',
        datatype: "json",
        colModel: [			
			{ label: 'id', name: 'id', index: 'id', width: 50, key: true },
			{ label: '教程名称', name: 'name', index: 'name', width: 80 },
            { label: '副标题', name: 'subhead', index: 'subhead', width: 80 },
			{ label: '教程简介', name: 'introduce', index: 'introduce', width: 80 },
			{ label: '图片', name: 'img', index: 'img', width: 80 ,hidden: true},
			{ label: '类型', name: 'typeName', index: 'type', width: 80 },
            { label: '作者', name: 'author', index: 'author', width: 80 },
			{ label: '上传者', name: 'uploadUser', index: 'upload_user', width: 80 },
			{ label: '', name: 'createTime', index: 'create_time', width: 80 ,hidden: true},
			{ label: '', name: 'updateTime', index: 'update_time', width: 80 ,hidden: true}
        ],
		viewrecords: true,
        height: 385,
        rowNum: 10,
		rowList : [10,30,50],
        rownumbers: true, 
        rownumWidth: 25, 
        autowidth:true,
        multiselect: true,
        pager: "#jqGridPager",
        jsonReader : {
            root: "page.list",
            page: "page.currPage",
            total: "page.totalPage",
            records: "page.totalCount"
        },
        prmNames : {
            page:"page", 
            rows:"limit", 
            order: "order"
        },
        gridComplete:function(){
        	//隐藏grid底部滚动条
        	$("#jqGrid").closest(".ui-jqgrid-bdiv").css({ "overflow-x" : "hidden" }); 
        }
    });

    // 上传图片
    $("#img").fileinput({
        language: 'zh',
        showUpload: true,
        showCaption: false,
        dropZoneEnabled: false,
        showRemove:false,
        allowedFileExtensions : ['jpg', 'png','gif'],
        maxFileCount:1,//上传图片最大数量
        uploadUrl: baseURL+"sys/file/uploadFile",
        browseClass: "btn btn-primary",
        previewFileIcon: "<i class='glyphicon glyphicon-king'></i>",
        layoutTemplates:{
            actionDelete:'',
            actionZoom:'',
            actionUpload:''
        }
    }).on("fileuploaded", function (e, data) {
        var res = data.response;
        if (res.code == 0) {
            alert('上传成功');
            vm.teach.img=res.path;
            // vm.song.opernName=res.fileName;
            //  alert(res.path);
        }
        else {
            alert('上传失败')
        }
    });
});

var vm = new Vue({
	el:'#rrapp',
	data:{
		showList: true,
		title: null,
		teach: {},
        q:{
            name:null,
            releaseTimeBegin:null,
            releaseTimeEnd:null
        },
        songList:[],
        index:1
	},
	methods: {
		query: function () {
            vm.q.releaseTimeBegin=$('#releaseTimeBeginId').val();
            vm.q.releaseTimeEnd=$('#releaseTimeEndId').val();
			vm.reload();
		},
		add: function(){
			vm.showList = false;
			vm.title = "新增";
			vm.teach = {};
            vm.songList=[];
            $("#myVedio").empty();
		},
		update: function (event) {
			var id = getSelectedRow();
			if(id == null){
				return ;
			}
			vm.showList = false;
            vm.title = "修改";
            
            vm.getInfo(id)
		},
		saveOrUpdate: function (event) {
            if(vm.teach.name==null||vm.teach.name==''){
                alert("请填写名称");
                return ;
            }
            if(vm.teach.subhead==null||vm.teach.subhead==''){
                alert("请填写副标题");
                return ;
            }
            if(vm.teach.introduce==null||vm.teach.introduce==''){
                alert("请填写简介");
                return ;
            }
            if(vm.teach.img==null||vm.teach.img==''){
                alert("请上传图片");
                return ;
            }
            if(vm.teach.type==null){
                alert("请选择类型");
                return ;
            }
            if(vm.teach.author==null||vm.teach.author==''){
                alert("请填写作者");
                return ;
            }
            if(vm.teach.uploadUser==null||vm.teach.uploadUser==''){
                alert("请填写上传者");
                return ;
            }
            var vedioList=$("#myVedio").find("li");
            var valiVedio=0;
                $.each(vedioList,function (index,item) {
                    var liId=$(item).attr("id");
                    liId = liId.split("vedio_")[1];
                    var vedioName=$("#vedioName_"+liId).val();
                    var vedioUrl=$("#vedioUrl_"+liId).val();
                    if(vedioName==null||vedioName==""||vedioUrl==null||vedioUrl==""){
                        valiVedio=1;
                    }
                });
                if(valiVedio==1){
                    alert("请填写完整视频信息");
                    return ;
                }
			var url = vm.teach.id == null ? "sys/teach/save" : "sys/teach/update";
			$.ajax({
				type: "POST",
			    url: baseURL + url,
                contentType: "application/json",
			    data: JSON.stringify(vm.teach),
			    success: function(r){
			    	if(r.code === 0){
                        if(vm.teach.id == null){
                            var ids=[];
                            $.each(vm.songList,function (index,item) {
                                ids.push(item.id);
                            });
                            //提交曲谱
                            $.ajax({
                                type: "POST",
                                url: baseURL + "sys/teach/teachSong",
                                contentType: "application/json",
                                data: JSON.stringify({teachId:r.teachId,songIds:ids}),
                                success: function(r){
                                    if(r.code == 0){
                                        alert('操作成功');
                                    }else{
                                        alert(r.msg);
                                    }
                                }
                            });
                            vm.teachVedio(r.teachId);
                            vm.reload();
                        }else{
                            vm.teachVedio(vm.teach.id);
                        }
					}else{
						alert(r.msg);
					}
				}
			});
		},
        teachVedio:function (teachId) {
            //提交视频
            var vedioList=$("#myVedio").find("li");
            var list=[];
            if(vedioList.length>0){
                $.each(vedioList,function (index,item) {
                    var liId=$(item).attr("id");
                    liId = liId.split("vedio_")[1];
                    var vedioName=$("#vedioName_"+liId).val();
                    var vedioUrl=$("#vedioUrl_"+liId).val();
                    var vedioIntroduce=$("#vedioIntroduce_"+liId).val();
                    var param={name:vedioName,url:vedioUrl,teachId:teachId,introduce:vedioIntroduce};
                    list.push(param);
                });
                $.ajax({
                    type: "POST",
                    url: baseURL + "sys/teach/teachVedio",
                    contentType: "application/json",
                    data: JSON.stringify(list),
                    success: function(r){
                        if(r.code == 0){
                            alert('操作成功', function(index){
                                vm.reload();
                            });
                        }else{
                            alert(r.msg);
                        }
                    }
                });
            }else{
                $.ajax({
                    type: "POST",
                    url: baseURL + "sys/teach/teachVedioDel",
                    data: {teachId:vm.teach.id},
                    success: function(r){
                        if(r.code == 0){
                            alert('操作成功', function(index){
                                vm.reload();
                            });
                        }else{
                            alert(r.msg);
                        }
                    }
                });
            }
        },
		del: function (event) {
			var ids = getSelectedRows();
			if(ids == null){
				return ;
			}
			
			confirm('确定要删除选中的记录？', function(){
				$.ajax({
					type: "POST",
				    url: baseURL + "sys/teach/delete",
                    contentType: "application/json",
				    data: JSON.stringify(ids),
				    success: function(r){
						if(r.code == 0){
							alert('操作成功', function(index){
								$("#jqGrid").trigger("reloadGrid");
							});
						}else{
							alert(r.msg);
						}
					}
				});
			});
		},
		getInfo: function(id){
			$.get(baseURL + "sys/teach/info/"+id, function(r){
                vm.teach = r.teach;
                $("#img").fileinput('refresh',{
                    initialPreview: '<img width="250px" height="150px" src="'+baseURL+"sys/file/getImg?path="+vm.teach.img+'" class="file-preview-image">'
                });
            });
            $.get(baseURL + "sys/teach/getSong/"+id, function(r){
                vm.songList = r.list;
            });
            $.get(baseURL + "sys/teach/getVedio/"+id, function(r){
                vm.vedioList = r.list;
                var str='';
                $.each(vm.vedioList,function (index,item) {
                    str+='<li style="margin-top: 10px;" class="list-group-item" id="vedio_'+index+'">' +
                        '视频名<input id="vedioName_'+index+'" class="form-control" value="'+item.name+'" />' +
                        '介绍<textarea maxlength="100" id="vedioIntroduce_'+index+'" class="form-control" rows="5">'+item.introduce+'</textarea>'+
                        // '介绍<input id="vedioIntroduce_'+index+'" class="form-control" value="'+item.introduce+'" />' +
                        '链接<input id="vedioUrl_'+index+'" class="form-control" value="'+item.url+'" />' +
                        '<a onclick="vm.uploadVedio('+index+');"><i class="fa fa-pencil-square-o"></i>选择视频</a>' +
                        '<a style="float: right;" onclick="vm.removeVedio('+index+');"><i class="fa fa-trash-o"></i>删除</a>' +
                        '</li>';
                });
                $("#myVedio").empty().append(str);
            });
		},
		reload: function (event) {
            $("#img").fileinput('clear');
			vm.showList = true;
			var page = $("#jqGrid").jqGrid('getGridParam','page');
			$("#jqGrid").jqGrid('setGridParam',{
                postData:{
                    name:vm.q.name,
                    releaseTimeBegin:vm.q.releaseTimeBegin,
                    releaseTimeEnd:vm.q.releaseTimeEnd
                },
                page:page
            }).trigger("reloadGrid");
		},
        addVedio:function () {
            var str='<li style="margin-top: 10px;" class="list-group-item" id="vedio_'+vm.index+'a">' +
                '视频名<input id="vedioName_'+vm.index+'a" class="form-control" placeholder="视频名(必填，1-25字)" />' +
                '介绍<textarea maxlength="100" id="vedioIntroduce_'+vm.index+'a" class="form-control" placeholder="介绍(非必填)" rows="5"></textarea>'+
                '链接<input id="vedioUrl_'+vm.index+'a" class="form-control" placeholder="链接(外链或上传视频)"/>' +
                '<a onclick="vm.uploadVedio(\''+vm.index+'a\');"><i class="fa fa-pencil-square-o"></i>选择视频</a>' +
                '<a style="float: right;" onclick="vm.removeVedio(\''+vm.index+'a\');"><i class="fa fa-trash-o"></i>删除</a>' +
                '</li>';
            $("#myVedio").append(str);
            vm.index=vm.index+1;
        },
        uploadVedio:function (index) {
            var layerIndex=layer.open({
                type: 1 ,//Page层类型
                area: ['500px', '500px'],
                title: '视频上传',
                shade: 0.6, //遮罩透明度,
                maxmin: false, //允许全屏最小化,
                anim: 1, //0-6的动画形式，-1不开启,
                // btn: ['提交'],
                // yes:function (index) {
                //
                // },
                content: '<input type="file" name="file" class="form-control" id="vedioFile_'+index+'"/>'
            });
            // 上传视频
            $("#vedioFile_"+index).fileinput({
                language: 'zh',
                showUpload: true,
                showCaption: false,
                dropZoneEnabled: false,
                showRemove:false,
                allowedFileExtensions : ['3gp','rmvb','flv','wmv','avi','mkv','mp4','mp3','wav'],
                maxFileCount:1,//上传图片最大数量
                uploadUrl: baseURL+"sys/file/uploadFile",
                browseClass: "btn btn-primary",
                // previewFileIcon: "<i class='glyphicon glyphicon-king'></i>",
                layoutTemplates:{
                    actionDelete:'',
                    actionZoom:'',
                    actionUpload:''
                }
            }).on("fileuploaded", function (e, data) {
                var res = data.response;
                if (res.code == 0) {
                    alert('上传成功');
                    $("#vedioUrl_"+index).val(res.path);
                    layer.close(layerIndex);
                    // vm.song.opernName=res.fileName;
                    //  alert(res.path);
                }
                else {
                    alert('上传失败')
                }
            });
        },
        removeVedio:function (id) {
            $("#vedio_"+id).remove();
        },
        openSongList:function () {
            var layerIndex=layer.open({
                type: 1 ,//Page层类型
                area: ['1000px', '800px'],
                title: '曲谱列表',
                shade: 0.6, //遮罩透明度,
                maxmin: false, //允许全屏最小化,
                anim: 1, //0-6的动画形式，-1不开启,
                btn: ['提交'],
                yes:function (index) {
                    if(vm.teach.id!=null&&vm.teach.id!=''){
                        var ids = $("#jqGridSong").jqGrid('getGridParam','selarrrow');
                        $.ajax({
                            type: "POST",
                            url: baseURL + "sys/teach/teachSong",
                            contentType: "application/json",
                            data: JSON.stringify({teachId:vm.teach.id,songIds:ids}),
                            success: function(r){
                                if(r.code == 0){
                                    alert('操作成功', function(index){
                                        $.get(baseURL + "sys/teach/getSong/"+vm.teach.id, function(r){
                                            vm.songList = r.list;
                                        });
                                        layer.closeAll();
                                    });
                                }else{
                                    alert(r.msg);
                                }
                            }
                        });
                    }else{
                        vm.songList=[];
                        var ids = $("#jqGridSong").jqGrid('getGridParam','selarrrow');
                        $.each(ids,function(index,item){
                            var rowData = $("#jqGridSong").jqGrid("getRowData",item);
                            vm.songList.push(rowData);
                        });
                        alert('操作成功', function(index){
                            layer.closeAll();
                        });
                    }
                },
                content: '<div style="padding:50px;">' +
                '<div class="grid-btn">' +
                '<div class="form-group col-sm-2">\n' +
                '<input type="text" class="form-control" id="songNameId" @keyup.enter="searchSong" placeholder="曲谱名称">\n' +
                '</div>' +
                '<a class="btn btn-default" onclick="vm.searchSong();">搜索</a>' +
                '</div>' +
                '<table id="jqGridSong"></table>' +
                '<div id="jqGridPagerSong"></div>' +
                '</div>'
            });
            layer.full(layerIndex);
            $("#jqGridSong").jqGrid({
                url: baseURL + 'sys/song/list',
                datatype: "json",
                colModel: [
                    { label: 'id', name: 'id', index: 'id', width: 50, key: true ,hidden: true},
                    { label: '曲谱名称', name: 'name', index: 'name', width: 80 },
                    { label: '曲谱难度', name: 'hardName', index: 'hard', width: 80 },
                    { label: '作者', name: 'author', index: 'author', width: 80 },
                    { label: '上架时间', name: 'releaseTime', index: 'release_time', width: 80 }
                ],
                viewrecords: true,
                height: 385,
                rowNum: 20,
                rowList : [20,50,100],
                rownumbers: true,
                rownumWidth: 25,
                autowidth:true,
                multiselect: true,
                pager: "#jqGridPagerSong",
                jsonReader : {
                    root: "page.list",
                    page: "page.currPage",
                    total: "page.totalPage",
                    records: "page.totalCount"
                },
                prmNames : {
                    page:"page",
                    rows:"limit",
                    order: "order"
                },
                gridComplete:function(){
                    //隐藏grid底部滚动条
                    $("#jqGrid").closest(".ui-jqgrid-bdiv").css({ "overflow-x" : "hidden" });
                },
                loadComplete:function(){
                    if (vm.songList.length > 0) {
                        $.each(vm.songList, function (i, item) {
                            $("#jqGridSong").jqGrid('setSelection',item.id);
                            // $("#jqg_jqGridSong_" + item.id).attr("checked", true);
                            // $("#jqGridSong").find("#"+item.id).attr("aria-selected",true).addClass("success");
                        });
                    }
                }
            });
        }
	}
});